import axios, { AxiosRequestConfig } from 'axios'

export interface IRes<T = unknown> {
  /** @deprecated TODO: 后续可能要改造，目前仅限拦截器中使用 */
  success: boolean
  /** @deprecated TODO: 后续可能要改造，目前仅限拦截器中使用 */
  errorMessage?: string | null
  /** @deprecated TODO: 后续可能要改造，目前仅限拦截器中使用 */
  code?: string | null
  /** 响应数据 */
  data?: T | null
}

export const getPath = (config: AxiosRequestConfig) => {
  return (
    axios
      .getUri(config)
      .split(/[?#]+/)[0]
      // 去除 origin，参考 https://github.com/axios/axios/blob/v1.7.7/lib/helpers/isAbsoluteURL.js
      .replace(/^([a-z][a-z\d+\-.]*:)?\/\/[^/]+/i, '')
      // 去除尾杠
      .replace(/\/+$/, '')
  )
}

export const getCustomServer = (type: ('oms' | 'tms' | (string & {})) | null | undefined) => {
  if (!type) return
  return sessionStorage.getItem(`fba_customServer_${type}`)?.match(/^https?:\/\/[^/?#]+/i)?.[0]
}

export const getDefaultErrMsg = (res: Partial<IRes>) => {
  const arrivedBackEnd = typeof res.success === 'boolean'
  return arrivedBackEnd ? '系统异常' : '请求异常'
}

export const isAppApi = (config: AxiosRequestConfig) => {
  if (import.meta.env.VITE_APP_ENV !== 'staging') {
    const path = axios.getUri(config)
    if (/^([a-z][a-z\d+\-.]*:)?\/\/[^/]+/i.test(path) && !path.startsWith(location.origin)) return false
  }
  const path = getPath(config)
  return path.startsWith('/api/') || path.startsWith('/tmsapi/') || path.startsWith('/omsapi/')
}
